<template>
  <div class="">
    <!-- 对话框 -->
    <el-dialog :title="tmform.id?'修改品牌':'添加品牌'" :visible.sync="dialogFormVisible">
      <el-form ref="thisFrom" style="width: 90%" :model="tmform" :rules="rules">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input v-model="tmform.tmName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="上传图片" label-width="100px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/kerwin/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="tmform.logoUrl" :src="tmform.logoUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
          <span>只能上传png、jpg文件，且单文件大小不能超过500kb</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleYes">确 定</el-button>
      </div>
    </el-dialog>
    <el-button
      type="primary"
      icon="el-icon-plus"
      style="margin: 10px 0px"
      @click="showDlg"
    >添加</el-button>
    <!-- 表格 -->
    <el-table border :data="tradeList.records">
      <el-table-column
        label="序号"
        width="80"
        align="center"
        type="index"
      />
      <el-table-column label="品牌名称" prop="tmName" />
      <el-table-column label="品牌LOGO">
        <slot slot-scope="{row,$index}">
          <img :src="row.logoUrl" style="height: 50px;">
        </slot>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="{row,$index}">
          <el-button type="warning" icon="el-icon-edit" size="mini" @click.native="updateDlg(row)">修改</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click.native="deleteDlg(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      align="center"
      style="margin-top: 30px; textalign: center"
      :total="tradeList.total"
      :current-page="page"
      :page-size="limit"
      :page-sizes="[3,5,10]"
      :page-count="7"
      layout="prev,pager,next,jumper,->,total,sizes"
      @current-change="getTrade"
      @size-change="sizeChange"
    />
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  name: 'MyTradeMark',

  data() {
    var validatorTmname = (rule, value, callback) => {
      console.log(rule, value, callback)
      if (value.length < 2 || value.length > 30) {
        return callback(new Error('品牌名称错误'))
      } else {
        callback()
      }
    }
    return {
      dialogFormVisible: false,
      page: 1,
      limit: 10,
      imageUrl: '',
      tmform: {
        logoUrl: '',
        tmName: ''
      },
      rules: {
        tmName: [
          { required: true, validator: validatorTmname, trigger: 'change' }
        ],
        logoUrl: [
          { required: true, message: '请选择品牌LOGO' }
        ]
      }
    }
  },
  computed: {
    ...mapState({
      tradeList(state) {
        console.log(state)
        return state.tradeList.tradeList
      }
    })
  },
  mounted() {
    this.getTrade()
  },
  methods: {
    deleteDlg(row) {
      console.log(this)
      this.$confirm(`此操作将永久删除${row.tmName}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: async(action, instance, done) => {
          if (action === 'confirm') {
            await this.$store.dispatch('deleteTradeAsync', row.id)
            this.getTrade(this.tradeList.records.length > 1 ? this.tradeList.current : this.tradeList.current - 1)
            done()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          } else {
            done()
            this.$message({
              type: 'warning',
              message: '用户取消删除!'
            })
          }
        }
      }).catch(() => {})
    },
    async handleYes() {
      this.$refs['thisFrom'].validate((val) => {
        if (val) {
          try {
            this.$store.dispatch('updateTradeAsync', this.tmform)
            this.getTrade(this.tmform.id ? this.page : 1)
            this.dialogFormVisible = false
          } catch (error) {
            console.log(error.message)
          }
        } else {
          return false
        }
      })
    },
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      console.log(res)
      this.tmform.logoUrl = res.data
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    showDlg() {
      this.dialogFormVisible = true
      this.tmform = {
        logoUrl: '',
        tmName: ''
      }
    },
    async updateDlg(row) {
      this.dialogFormVisible = true
      this.tmform = { ...row }
    },
    sizeChange(val) {
      this.limit = val
      this.getTrade()
    },
    // changeIndex(val) {
    //   this.page = val
    //   this.getTrade()
    // },
    getTrade(val = 1) {
      this.page = val
      this.$store.dispatch('getTradeListAsync', { page: this.page, limit: this.limit })
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
